package com.xqls.biz.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xqls.bean.CompanyBean;
import com.xqls.biz.DrainFlowRecordBiz;
import com.xqls.service.CompanyService;
import com.xqls.service.DrainFlowRecordService;
import com.xqls.util.CommonPage;
import com.xqls.util.CommonResult;
import com.xqls.util.GetKeyByValue;
import com.xqls.util.DownloadAct;
import com.xqls.util.VelocityUtil;

@Service
public class DrainFlowRecordBizImpl implements DrainFlowRecordBiz {
	@Autowired
	private DrainFlowRecordService flowService;
	@Autowired
	private CompanyService companyService;
	private static Logger logger = Logger.getLogger(DrainFlowRecordBiz.class);

	/**
	 * 分钟记录
	 */
	@SuppressWarnings("unchecked")
	@Override
	public CommonResult getFlowRecordByPage(CommonPage commonPage, HttpServletRequest request, HttpServletResponse response) {
		CommonResult result = new CommonResult();
		try {
			commonPage.setPageData(flowService.selMinRecordByMap(commonPage.pageToMap()));
			Map<String, Object> mapList = selNewDayCumulativeFlow(commonPage);
			((Map<String, Object>) mapList.get("showMap")).put("companyName", mapList.get("companyName"));
			((Map<String, Object>) mapList.get("showMap")).put("minRecordList", mapList.get("listMap"));
			commonPage.setHtml(VelocityUtil.getHtmlByMap("drainFlowRecord/drainMinFlowRecordListData.vm",
					(Map<String, Object>) mapList.get("showMap"),request,response,request.getSession().getServletContext()));
			result.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("查询分钟流量列表异常", e);
		}
		return result;
	}

	/**
	 * 公共方法，查询企业名称，查询数据
	 * 
	 * @param commonPage
	 * @return
	 */
	public Map<String, Object> selNewDayCumulativeFlow(CommonPage commonPage) {
		Map<String, Object> mapList = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> page = commonPage.pageToMap();
		Map<String, Object> newPage = new HashMap<String, Object>();
		newPage.put("month", page.get("month"));
		newPage.put("dateTime", page.get("dateTime"));
		newPage.put("enterpriseNo", page.get("enterpriseNo"));
		map = flowService.selDayCumulativeFlow(newPage);
		Map<String, Object> showMap = new HashMap<String, Object>();
		if (map != null && map.size() > 0) {
			showMap.put("hasData", map);
			showMap.put("MaxRecord", map.get("MaxRecord"));
			showMap.put("MinRecord", map.get("MinRecord"));
		} else {
			showMap.put("hasData", null);
		}
		CommonResult commonresult = companyService.queryByDeviceNo((String) page.get("enterpriseNo"));
		CompanyBean companyBean = (CompanyBean) commonresult.getData();
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> listMap = (List<Map<String, Object>>) commonPage.getPageData();
		if (commonPage.curr > 1) {
			int j = (commonPage.curr - 1) * (commonPage.pageSize);
			for (int i = j; i < (listMap.size() + j); i++) {
				listMap.get(i - j).put("no", i + 1);
			}
		} else {
			for (int i = 0; i < listMap.size(); i++) {
				listMap.get(i).put("no", i + 1);
			}
		}
		mapList.put("companyName", companyBean.getCompanyName());
		mapList.put("listMap", listMap);
		mapList.put("companyBean", companyBean);
		mapList.put("showMap", showMap);
		mapList.put("page", page);
		return mapList;
	}

	/**
	 * 小时记录
	 */
	@SuppressWarnings("unchecked")
	@Override
	public CommonResult getHourFlowRecordByPage(CommonPage commonPage, HttpServletRequest request, HttpServletResponse response) {
		CommonResult result = new CommonResult();
		try {
			commonPage.setPageData(flowService.selHourRecordByMap(commonPage.pageToMap()));
			Map<String, Object> mapList = selNewDayCumulativeFlow(commonPage);
			((Map<String, Object>) mapList.get("showMap")).put("companyName", mapList.get("companyName"));
			((Map<String, Object>) mapList.get("showMap")).put("hourRecordList", mapList.get("listMap"));
			commonPage.setHtml(VelocityUtil.getHtmlByMap("drainFlowRecord/drainHourFlowRecordListData.vm",
					(Map<String, Object>) mapList.get("showMap"),request,response,request.getSession().getServletContext()));
			result.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("查询小时流量列表异常", e);
		}
		return result;
	}

	/**
	 * 日记录
	 */
	@SuppressWarnings("unchecked")
	@Override
	public CommonResult getDayFlowRecordByPage(CommonPage commonPage, HttpServletRequest request, HttpServletResponse response) {
		CommonResult result = new CommonResult();
		try {
			Calendar calendar = Calendar.getInstance(); //创建calendar对象
			Map<String, Object> lastMax = flowService.selectLastMaxBeforeThis(commonPage.pageToMap());//求出本月之前最大流量
			List<Map<String, Object>> mapList = flowService.selDayRecordByMap(commonPage.pageToMap());
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM");
			calendar.setTime(format1.parse(commonPage.getParamMap().get("month").toString()));
			calendar.set(Calendar.DATE, 1);
			calendar.roll(Calendar.DATE, -1);
			 Map[] list=new Map[calendar.get(Calendar.DATE)];
			 
				for(int i=0;i<mapList.size();i++){
					calendar.setTime(format.parse(mapList.get(i).get("riqi").toString()));
					Map<String, Object> map1 = new HashMap<String, Object>();
					if(i==0){
						map1.put("no", calendar.get(Calendar.DATE));
						map1.put("riqi", format.format(calendar.getTime()));
						map1.put("paiFang", Double.parseDouble(mapList.get(i).get("MaxRecord").toString())-Double.parseDouble(lastMax.get("lastMax").toString()));
						map1.put("MinRecord", Double.parseDouble(lastMax.get("lastMax").toString()));
						map1.put("MaxRecord", mapList.get(i).get("MaxRecord"));
						list[calendar.get(Calendar.DATE)-1]=map1;
						
					}else{
							map1.put("no", calendar.get(Calendar.DATE));
							map1.put("riqi", format.format(calendar.getTime()));
							map1.put("paiFang", Double.parseDouble(mapList.get(i).get("MaxRecord").toString())-Double.parseDouble(mapList.get(i-1).get("MaxRecord").toString()));
							map1.put("MinRecord", Double.parseDouble(mapList.get(i-1).get("MaxRecord").toString()));
							map1.put("MaxRecord", mapList.get(i).get("MaxRecord"));
							list[calendar.get(Calendar.DATE)-1]=map1;
						}
					}
				for(int j=0;j<list.length;j++){
					Map<String, Object> map1 = new HashMap<String, Object>();
					if(list[j]==null){
						map1.put("no", j+1);
						map1.put("riqi", format.format(format.parse(commonPage.getParamMap().get("month").toString()+"-"+(j+1))));
						map1.put("paiFang", "-----");
						map1.put("MinRecord", "-----");
						map1.put("MaxRecord", "-----");
						list[j]=map1;
					}
				}
				Map<String, Object> showMap = new HashMap<String, Object>();
				Map<String, Object> map = new HashMap<String, Object>();
				map = flowService.selectMapFromDayFlow(commonPage.pageToMap());
				if (map != null && map.size() > 0) {
					showMap.put("hasData", map);
					showMap.put("sum", Double.parseDouble(map.get("cumulativeFlow").toString())-Double.parseDouble(lastMax.get("lastMax").toString()));
				} else {
					showMap.put("hasData", null);
				}
				CommonResult commonresult = companyService.queryByDeviceNo((String) commonPage.pageToMap().get("enterpriseNo"));
				CompanyBean companyBean = (CompanyBean) commonresult.getData();
				showMap.put("companyName", companyBean.getCompanyName());
				showMap.put("dayRecordList", list);
				commonPage.setHtml(VelocityUtil.getHtmlByMap("drainFlowRecord/drainDayFlowRecordListData.vm",showMap
						,request,response,request.getSession().getServletContext()));
			result.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("查询日流量列表异常", e);
		}
		return result;
	}

	/**
	 * 月统计
	 */
	@Override
	public CommonResult getMonthFlowRecordByPage(CommonPage commonPage, HttpServletRequest request, HttpServletResponse response) {
		CommonResult result = new CommonResult();
		try {
			// 通过区号查询区下的所有设备
			Map<String, Object> companyMap = new HashMap<String, Object>();
			companyMap.put("blockUrl", commonPage.getParamMap().get("block"));
			companyMap.put("deviceType", Integer.parseInt(String.valueOf(commonPage.getParamMap().get("deviceType"))));
			List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
			List<Map<String, Object>> companyList = companyService.queryByMap(companyMap);
			if(companyList.size()>0){
			List<String> deviceList = new ArrayList<String>();
			for (Map<String, Object> map : companyList) {
				deviceList.add((String) map.get("deviceNo"));
			}
			commonPage.paramMap.put("list", deviceList);

			commonPage.paramMap.put("date", commonPage.getParamMap().get("month"));
			List<Map<String, Object>> listmap = flowService.selMonthRecordByMap(commonPage.pageToMap());
			listMap = GetKeyByValue.getLastMonthByThisMonth(listmap);
			if (commonPage.curr > 1) {
				int j = (commonPage.curr - 1) * (commonPage.pageSize);
				for (int i = j; i < (listMap.size() + j); i++) {
					listMap.get(i - j).put("no", i + 1);
					if (listMap.get(i - j).get("MinCumulativeFlow") == null) {
						listMap.get(i - j).put("MinCumulativeFlow", "   -----");
						listMap.get(i - j).put("balance", "   -----");
					} else if (listMap.get(i).get("MaxCumulativeFlow") == null) {
						listMap.get(i - j).put("MaxCumulativeFlow", "   -----");
						listMap.get(i - j).put("balance", "   -----");
					} else {
						listMap.get(i - j).put("balance", (Double) listMap.get(i - j).get("MaxCumulativeFlow")
								- (Double) listMap.get(i - j).get("MinCumulativeFlow"));
					}
				}
			} else {
				for (int i = 0; i < listMap.size(); i++) {
					listMap.get(i).put("no", i + 1);
					if (listMap.get(i).get("MinCumulativeFlow") == null) {
						listMap.get(i).put("MinCumulativeFlow", "   -----");
						listMap.get(i).put("balance", "   -----");
					} else if (listMap.get(i).get("MaxCumulativeFlow") == null) {
						listMap.get(i).put("MaxCumulativeFlow", "   -----");
						listMap.get(i).put("balance", "   -----");
					} else {
						listMap.get(i).put("balance", (Double) listMap.get(i).get("MaxCumulativeFlow")
								- (Double) listMap.get(i).get("MinCumulativeFlow"));
					}

				}
			}}
			else{
				listMap=null;
			}
			Map<String, Object> showMap = new HashMap<String, Object>();
			showMap.put("monthRecordList", listMap);
			commonPage.setHtml(VelocityUtil.getHtmlByMap("drainFlowRecord/drainMonthFlowRecordListData.vm", showMap,request,response,request.getSession().getServletContext()));
			result.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("查询月统计列表异常", e);
		}
		return result;
	}

	/**
	 * 年统计
	 */
	@Override
	public CommonResult getYearFlowRecordByPage(Map<String, Object> commonPage, HttpServletRequest request, HttpServletResponse response) {
		CommonResult result = new CommonResult();
		CommonPage common = new CommonPage();
		try {
			Map<String, Object> companyMap = new HashMap<String, Object>();
			companyMap.put("blockUrl", commonPage.get("block"));
			companyMap.put("deviceType", Integer.parseInt(String.valueOf(commonPage.get("deviceType"))));
			List<Map<String, Object>> companyList = companyService.queryByMap(companyMap);
			List<String> deviceList = new ArrayList<String>();
			for (Map<String, Object> map : companyList) {
				deviceList.add((String) map.get("deviceNo"));
			}
			commonPage.put("list", deviceList);
			List<Map<String, Object>> listMap = flowService.selYearRecordByMap(commonPage);
			Map<String, Object> sumMap = flowService.selectYearColumn(commonPage);
			
				for (int i = 0; i < listMap.size(); i++) {
					listMap.get(i).put("no", i + 1);
				}
			
			Map<String, Object> showMap = new HashMap<String, Object>();
			showMap.put("yearRecordList", listMap);
			showMap.put("yearClumSum", sumMap);
			showMap.put("no", listMap.size() + 1);
			common.setHtml(VelocityUtil.getHtmlByMap("drainFlowRecord/drainYearFlowRecordListData.vm", showMap,request,response,request.getSession().getServletContext()));
			result.setData(common);
			result.setIsSuccess(true);
		} catch (Exception e) {
			logger.error("查询年统计列表异常", e);
		}
		return result;
	}

	/**
	 * 生成记录
	 */
	@Override
	public CommonResult generateRecord(Map<String, Object> map) {
		CommonResult result = new CommonResult();
		try {
			boolean boo = flowService.insertToDay(map);
			boolean boo1 = flowService.insertToMonth(map);
			if (boo == true && boo1 == true) {
				result.setIsSuccess(true);
			} else {
				result.setIsSuccess(false);
			}
		} catch (Exception e) {
			logger.error("生成记录异常", e);
		}
		return result;
	}

	@Override
	public CommonResult getMinuteFlowRecordByMap(HttpServletRequest request, HttpServletResponse response,
			Map<String, Object> map) {
		CommonResult result = new CommonResult();
		try {
			List<Map<String, Object>> recordList = this.flowService.getMinuteListByMap(map);
			if(recordList.isEmpty())
			{
				result.setResultMsg("没有数据");
			}
			else
			{
                String sheetName="排放口分钟流量统计";
				Set<String> keySet = recordList.get(0).keySet();
				String []keys=keySet.toArray(new String[keySet.size()]);
				String columnNames[]={"序号","排放口","记录时间","瞬时流量","累计流量"};
				DownloadAct.excelDownload(request, response, recordList, columnNames, keys, sheetName);
				result.setIsSuccess(true);
			}
		} catch (Exception e) {
			logger.error("导出分钟流量统计异常", e);
		}
		return result;
	}

	@Override
	public CommonResult getHourFlowRecordByMap(HttpServletRequest request, HttpServletResponse response,
			Map<String, Object> map) {
		CommonResult result = new CommonResult();
		try {
			List<Map<String, Object>> recordList = this.flowService.getHourListByMap(map);
			if(recordList.isEmpty())
			{
				result.setResultMsg("没有数据");
			}
			else
			{
                String sheetName="排放口小时流量统计";
				Set<String> keySet = recordList.get(0).keySet();
				String []keys=keySet.toArray(new String[keySet.size()]);
				String columnNames[]={"序号","排放口","记录时间","排量","瞬时流量","累计流量"};
				DownloadAct.excelDownload(request, response, recordList, columnNames, keys, sheetName);
				result.setIsSuccess(true);
			}
		} catch (Exception e) {
			logger.error("导出小时流量统计异常", e);
		}
		return result;
	}

	@Override
	public CommonResult getDayFlowRecordByMap(HttpServletRequest request, HttpServletResponse response,
			Map<String, Object> map) {
		CommonResult result = new CommonResult();
		try {
			List<Map<String, Object>> recordList = this.flowService.getDayListByMap(map);
			if(recordList.isEmpty())
			{
				result.setResultMsg("没有数据");
			}
			else
			{
                String sheetName="排放口日期流量统计";
				Set<String> keySet = recordList.get(0).keySet();
				String []keys=keySet.toArray(new String[keySet.size()]);
				String columnNames[]={"序号","排放口","记录时间","排量","瞬时流量","累计流量"};
				DownloadAct.excelDownload(request, response, recordList, columnNames, keys, sheetName);
				result.setIsSuccess(true);
			}
		} catch (Exception e) {
			logger.error("导出日期钟流量统计异常", e);
		}
		return result;
	}

	@Override
	public CommonResult getMonthFlowRecordByMap(HttpServletRequest request, HttpServletResponse response,
			Map<String, Object> map) {
		CommonResult result = new CommonResult();
		try {
			List<Map<String, Object>> recordList = this.flowService.getMonthListByMap(map);
			if(recordList.isEmpty())
			{
				result.setResultMsg("没有数据");
			}
			else
			{
                String sheetName="排放口月份流量统计";
				Set<String> keySet = recordList.get(0).keySet();
				String []keys=keySet.toArray(new String[keySet.size()]);
				String columnNames[]={"序号","排放口","上月抄表","上月读数","本月抄表","本月读数","本月取水量"};
				DownloadAct.excelDownload(request, response, recordList, columnNames, keys, sheetName);
				result.setIsSuccess(true);
			}
		} catch (Exception e) {
			logger.error("导出月份流量统计异常", e);
		}
		return result;
	}

	@Override
	public CommonResult getYearFlowRecordByMap(HttpServletRequest request, HttpServletResponse response,
			Map<String, Object> map) {
		CommonResult result = new CommonResult();
		try {
			List<Map<String, Object>> recordList = this.flowService.getYearListByMap(map);
			if(recordList.isEmpty())
			{
				result.setResultMsg("没有数据");
			}
			else
			{
                String sheetName="排放口年份流量统计";
				Set<String> keySet = recordList.get(0).keySet();
				String []keys=keySet.toArray(new String[keySet.size()]);
				String columnNames[]={"序号","排放口","1月份","2月份","3月份","4月份","5月份","6月份","7月份","8月份","9月份","10月份","11月份","12月份","合计"};
				DownloadAct.excelDownload(request, response, recordList, columnNames, keys, sheetName);
				result.setIsSuccess(true);
			}
		} catch (Exception e) {
			logger.error("导出年份流量统计异常", e);
		}
		return result;
	}

}
